package com.bieber.democamp.multidatabase;

import javax.sql.DataSource;
import javax.xml.crypto.Data;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;
import java.util.logging.Logger;

/**
 * Created by bieber on 2015/10/26.
 */
public class MultiDataSource implements DataSource {
    
    private List<DataSource> readDataSource;
    
    private DataSource writeDataSource;
    
    private AtomicLong readCounter = new AtomicLong();
    
    public DataSource selectReadDB(){
        long index = readCounter.getAndIncrement();
        return readDataSource.get((int) (index%readDataSource.size()));
    }
    
    @Override
    public Connection getConnection() throws SQLException {
        return new ConnectionWrapper(this);
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return new ConnectionWrapper(this,username,password);
    }

    public DataSource getWriteDataSource() {
        return writeDataSource;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        throw new UnsupportedOperationException();
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {
        throw new UnsupportedOperationException();
    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
        throw new UnsupportedOperationException();
    }

    @Override
    public int getLoginTimeout() throws SQLException {
        throw new UnsupportedOperationException();
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        throw new UnsupportedOperationException();
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        throw new UnsupportedOperationException();
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        throw new UnsupportedOperationException();
    }

    public void setReadDataSource(List<DataSource> readDataSource) {
        this.readDataSource = readDataSource;
    }

    public void setWriteDataSource(DataSource writeDataSource) {
        this.writeDataSource = writeDataSource;
    }
}
